package com.fary.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fary.dto.PaymentInfoDTO;
import com.fary.entity.PaymentInfo;
import com.fary.holder.PaymentInfoHolder;
import com.fary.mapper.PaymentInfoMapper;
import com.fary.service.OpenPaymentCoreService;
import com.fary.util.TokenUtils;
import com.fary.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.fary.constant.PayConstant.PAY_PAYMENT_COMPLETED;
import static com.fary.constant.PayConstant.PAY_PREFIX;

@Service
public class OpenPaymentCoreServiceImpl implements OpenPaymentCoreService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Override
    public String createPayToken(PaymentInfoDTO paymentInfoDto) {
        // 1.将dto转化do
        PaymentInfo paymentInfo = new PaymentInfo();
        BeanUtil.copyProperties(paymentInfoDto, paymentInfo);
        // 2.插入数据
        int insertResult = paymentInfoMapper.insert(paymentInfo);
        if (insertResult == 0) {
            return null;
        }
        // 3.生成对应的支付令牌
        Integer payId = paymentInfo.getId();
        String payToken = TokenUtils.getToken(PAY_PREFIX);
        redisCache.setCacheObject(payToken, String.valueOf(payId));
        return payToken;
    }

    @Override
    public PaymentInfo getPayTokenPaymentInfo(String payToken) {
        String payIdStr = redisCache.getCacheObject(payToken);
        if (StrUtil.isEmpty(payIdStr)) {
            return null;
        }
        Integer payId = Integer.parseInt(payIdStr);
        // 根据payid查询支付的信息
        PaymentInfo paymentInfo = paymentInfoMapper.selectById(payId);
        return paymentInfo;
    }

    public PaymentInfo getOrderIdByPaymentInfo(String orderId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ORDER_ID", orderId);
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(queryWrapper);
        return paymentInfo;
    }


    @Override
    @Transactional
    public int updatePaymentStatus(PaymentInfo paymentInfo, Integer paymentStatus) {
        paymentInfo.setPaymentStatus(paymentStatus);
        int result = paymentInfoMapper.updateById(paymentInfo);
        PaymentInfoHolder.set(paymentInfo);
        return result;
    }

    @Transactional
    public int updatePaymentStatusOk(PaymentInfo paymentInfo) {
        paymentInfo.setPaymentStatus(PAY_PAYMENT_COMPLETED);
        int result = paymentInfoMapper.updateById(paymentInfo);
        return result;
    }
}
